<template>
  <div class="flex-column">
    <div class="mb-10">
      <el-button
        v-if="getUser.userId === 'admin'"
        type="primary"
        icon="el-icon-plus"
        @click="add"
      >{{ $t('ADD') }}</el-button>
    </div>
    <TableView
      :table-header="tableHeader"
      :table-data="tableData"
      :operate-width="210"
      :options="{ pagination: false, sequence: false }"
      @operate="operate"
    />
    <edit :visible="editShow" :type="operateType" :data="row" @close="close" />
    <component
      :is="bindAreaShow ? 'BindAreaForm' : ''"
      :dialog-visible.sync="bindAreaShow"
      :bind-area-form="bindAreaForm"
    />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import UserApi from '@/api/system/UserApi'
  import OrgApi from '@/api/system/OrgApi'
  import OrgRegionApi from '@/api/basebiz/OrgRegionApi.js'
  import BindAreaForm from './components/BindAreaForm'
  import Edit from './Edit'
  import TableView from '@/components/TableView'

  export default {
    name: 'SystemOrg',
    components: { Edit, BindAreaForm, TableView },
    data() {
      return {
        tableData: [],
        row: {},
        operateType: 'add',
        editShow: false,
        bindAreaShow: false,
        bindAreaForm: {
          orgId: '',
          orgName: '',
          regionIds: []
        },
        tableHeader: [
          {
            label: 'ORGANIZATIONCODE',
            prop: 'orgId',
            width: '200',
            fixed: 'left',
            configType: 'default'
          },
          {
            label: 'ORGANIZATION_NAME',
            prop: 'orgName',
            configType: 'default'
          },
          {
            label: 'ORG_TYPE',
            prop: 'orgTypename',
            configType: 'default'
          },
          {
            label: 'CONTACT_PERSON',
            prop: 'person',
            configType: 'extend'
          },
          {
            label: 'CONTACT_NUMBER',
            prop: 'tel',
            configType: 'extend'
          },
          {
            label: 'EMAIL',
            prop: 'email',
            configType: 'extend'
          },
          {
            label: 'ADDRESS',
            prop: 'address',
            configType: 'extend'
          }
        ]
      }
    },
    computed: {
      ...mapGetters(['dictMap', 'getUser']),
      permission() {
        return this.$store.getters.getAuthData('sys:org')
      }
    },
    created() {
      this.loadData()
    },
    methods: {
      loadData() {
        OrgApi.tree().then(res => {
          const list = res || []
          this.formatData(list)
          this.tableData = list
        })
      },
      formatData(data) {
        data.forEach(i => {
          i.orgTypename = this.dictMap.ORG_TYPE[i.orgType]
          i.btns = this.getBtns(i)
          if (i.children) {
            this.formatData(i.children)
          }
        })
      },
      getBtns(row) {
        const btns = [
          {
            key: 'view',
            show: true,
            label: 'VIEW'
          },
          {
            key: 'addChild',
            show: this.permission.add,
            label: 'ADD_CHILD'
          },
          {
            key: 'mod',
            show: this.permission.mod && row.orgId !== 'manager_100000',
            label: 'MOD'
          },
          {
            key: 'bindingArea',
            show: this.permission.region && row.orgId !== 'manager_100000',
            label: 'BIND_AREA'
          },
          {
            key: 'del',
            show: this.permission.del && !row.children && row.orgId !== 'manager_100000',
            label: 'DEL'
          },
          {
            key: 'moveUp',
            show: this.permission.moveup,
            label: 'MOVE_UP'
          },
          {
            key: 'moveDown',
            show: this.permission.movedown,
            label: 'MOVE_DOWN'
          }
        ]
        return btns.filter(i => i.show)
      },
      // 操作
      operate(data) {
        switch (data.type) {
        case 'view':
          this.operateType = 'view'
          this.row = data.data
          this.editShow = true
          break
        case 'addChild':
          this.addChild(data.data)
          break
        case 'mod':
          this.operateType = 'mod'
          this.row = data.data
          this.editShow = true
          break
        case 'bindingArea':
          this.bindAreaShow = !this.bindAreaShow
          this.bindAreaForm = data.data
          break
        case 'del':
          this.del(data.data)
          break
        case 'moveUp':
          this.up(data.data)
          break
        case 'moveDown':
          this.down(data.data)
          break
        }
      },
      search() {
        this.loadData()
      },
      add() {
        this.operateType = 'add'
        this.row = {}
        this.editShow = true
      },
      async del(row) {
        // 查询是否有用户已绑定该机构
        const res = await UserApi.list({ orgId: row.orgId })
        if (res && res.length) {
          this.$message.error(
            this.$t('ORG_HAS_USER', { name: row.orgName, user: res.map(i => i.userId).join('、') })
          )
          return
        }
        // 查询是否有区域已绑定该机构
        const authList = await OrgRegionApi.regionAuth({ orgId: row.orgId })
        if (authList && authList.length && authList.join(',') !== '$') {
          this.$message.error(
            this.$t('ORG_HAS_AREA', { name: row.orgName })
          )
          return
        }
        this.$confirm(
          this.$t('CONFIRM_DELETION_PROMPT_TIP', {
            key: this.$t('INSTITUTION'),
            value: row.orgName
          }),
          { type: 'warning' }
        )
          .then(() => {
            this.delOrg(row)
          })
          .catch(() => {})
      },
      async delOrg(row) {
        const result = await OrgApi.del(row.id, { orgName: row.orgName, orgId: row.orgId })
        if (result) {
          this.$message.success(this.$t('DELETE_SUCCESS'))
          this.loadData()
        }
      },
      addChild(row) {
        this.operateType = 'add'
        this.row = {
          parentId: row.orgId,
          orgType: row.orgType
        }
        this.editShow = true
      },
      up(row) {
        OrgApi.up(row).then(result => {
          if (result) {
            this.$message.success(this.$t('MOVE_UP_COMPLETED'))
            this.loadData()
          }
        })
      },
      down(row) {
        OrgApi.down(row).then(result => {
          if (result) {
            this.$message.success(this.$t('MOVE_DOWN_COMPLETED'))
            this.loadData()
          }
        })
      },
      close(load) {
        this.editShow = false
        if (load === true) {
          this.loadData()
        }
      }
    }
  }
</script>

<style scoped></style>
